<template>
  <view class="add_student_form">
    <view class="top_tip">此页面用于添加学员信息，包括昵称和头像，并准备进行身份认证</view>
    <u-form :model="form" labelWidth="220" ref="uForm" label-position="top">
      <view class="box">
        <u-form-item label="昵称" prop="nickName"><u-input v-model="form.nickName" placeholder="请输入" /></u-form-item>
        <u-form-item label="头像上传" prop="avatarUrl">
          <u-upload :file-list="avatorFileList" :header="{ token, version }" :action="avatorAction" @afterRead="afterRead" :max-count="1" />
        </u-form-item>
        <u-form-item label="身份证照片上传" prop="idNumber">
          <u-upload :disabled="readonly" :action="action" :file-list="fileList" :max-count="1" @afterRead="afterReadCard"></u-upload>
        </u-form-item>
      </view>
      <view class="line"></view>
      <view class="box">
        <view class="u-form-item">自动识别的身份证信息</view>
        <view class="form_tip">
          <view class="tip tip1">字段</view>
          <view class="tip">信息</view>
        </view>

        <u-form-item label-position="left" :border-bottom="true" label="公民身份证号码" prop="idNumber">
          <u-input :disabled="readonly" v-model="form.idNumber" placeholder="请输入" />
        </u-form-item>
        <u-form-item label-position="left" label="姓名" prop="name">
          <u-input :disabled="readonly" v-model="form.name" placeholder="请输入" />
        </u-form-item>
        <u-form-item label-position="left" label="性别" prop="gender">
          <u-input :disabled="readonly" v-model="form.gender" placeholder="请输入" />
        </u-form-item>
        <u-form-item label-position="left" label="民族" prop="ethnic">
          <u-input :disabled="readonly" v-model="form.ethnic" placeholder="请输入" />
        </u-form-item>
        <u-form-item label-position="left" label="地址" prop="address">
          <u-input :disabled="readonly" v-model="form.address" placeholder="请输入" />
        </u-form-item>
      </view>
    </u-form>

    <view class="box action_btn">
      <view class="btn btn1" @click="back">返回</view>
      <view class="btn btn2" @click="confimAdd">确认</view>
    </view>
  </view>
</template>

<script>
import { addStudent, updateStudentInfo, ocrIdCard } from '@/api/class_share';
import { baseURL, version } from '@/config/app.js';
import store from '@/store';
export default {
  data() {
    return {
      id: '',
      readonly: false,
      version,
      token: store.getters.token,
      form: {
        nickName: '',
        name: '',
        idNumber: '',
        gender: '',
        birthDate: '', // 根据身份证号码推算出的出生日期
        avatarUrl: '',
        address: '',
        ethnic: '',
        idCardFrontUrl: '',
      },
      rules: {
        nickName: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        name: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        idNumber: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        gender: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        birthDate: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        avatarUrl: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        address: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        ethnic: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
        idCardFrontUrl: [
          {
            required: true,
            message: '请输入',
            trigger: ['change', 'blur'],
          },
        ],
      },
      // 头像
      avatorAction: baseURL + '/shopapi/upload/image',
      avatorFileList: [],
      // 身份证
      action: 'https://duguang.aliyun.com/experience?type=standardsubtype=idcard#intro',
      fileList: [],
    };
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  onLoad(options) {
    this.readonly = false;
    const { id } = options;
    this.id = id;
    if (this.id) {
      this.readonly = true;
    }
  },
  methods: {
    afterRead(event) {
      // 添加图片大小限制
      const maxSize = 5 * 1024 * 1024; // 5MB
      if (event.file.size > maxSize) {
        this.$u.toast('图片大小不能超过5MB');
        return;
      }
      this.avatorFileList.push({
        url: event.file.url,
      });
      this.form.avatarUrl = event.file.url;
    },
    afterReadCard(event) {
      // 添加图片大小限制
      const maxSize = 10 * 1024 * 1024; // 10MB
      if (event.file.size > maxSize) {
        this.$u.toast('图片大小不能超过10MB');
        return;
      }

      this.fileList.push({
        url: event.file.url,
      });

      // 将图片转换为base64
      uni.getFileSystemManager().readFile({
        filePath: event.file.url,
        encoding: 'base64',
        success: res => {
          // 调用身份证OCR识别接口
          ocrIdCard({
            side: 'face',
            image_base64: res.data,
          })
            .then(response => {
              const data = response.data;
              // 更新表单数据
              this.form.idNumber = data.number;
              this.form.gender = data.sex;
              this.form.birthDate = data.birth;
              this.form.address = data.address;
              this.form.ethnic = data.nationality;
              this.form.name = data.name;
              this.form.idCardFrontUrl = event.file.url;
            })
            .catch(err => {
              this.$u.toast('身份证识别失败');
            });
        },
        fail: () => {
          this.$u.toast('图片读取失败');
        },
      });
    },
    confimAdd() {
      if (this.id) {
        const { nickName, avatarUrl } = this.form;
        const params = { nickName, avatarUrl, id: this.id };
        if (nickName && avatarUrl) {
          updateStudentInfo(params).then(res => {
            this.$u.toast('修改成功');
          });
        } else {
          this.$u.toast('请填写完整');
        }
      } else {
        this.$refs.uForm.validate(valid => {
          if (valid) {
            addStudent(this.form).then(res => {
              this.$u.toast('添加成功');
            });
          } else {
            this.$u.toast('请填写完整');
          }
        });
      }
      // this.back();
    },
    back() {
      this.$router.go(-1);
    },
  },
};
</script>
<style lang="scss" scoped>
.add_student_form {
  .top_tip {
    width: 100%;
    height: 60rpx;
    background: #edfff6;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 24rpx;
    color: #0dc160;
    line-height: 60rpx;
    text-align: center;
  }
  .box {
    padding: 40rpx 32rpx;
    background: #fff;
  }
  .line {
    height: 24rpx;
    width: 100%;
    background: #f8f8f8;
  }
  .form_tip {
    display: flex;
    align-items: center;
    .tip {
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 24rpx;
      color: #999999;
      margin: 40rpx 0 24rpx 0;
    }
    .tip1 {
      width: 220rpx;
    }
  }

  .action_btn {
    display: flex;
    .btn {
      height: 90rpx;
      border-radius: 44rpx;
      border: 1rpx solid #d5d5d5;
      text-align: center;
      line-height: 90rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      font-size: 30rpx;
      flex: 1;
    }
    .btn1 {
      color: #000000;
      background: #ffffff;
      margin-right: 24rpx;
    }
    .btn2 {
      color: #ffffff;
      background: #0dc160;
    }
  }
}
</style>
